package com.zzb.weixin.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zzb.weixin.WeiXinUtil;
import com.zzb.weixin.listener.DefaultHandleMessageListener;
import com.zzb.weixin.listener.DefaultListenerManager;
import com.zzb.weixin.model.event.EventMsg;
import com.zzb.weixin.model.msg.basic.ImageMsg;
import com.zzb.weixin.model.msg.basic.ImageTextData;
import com.zzb.weixin.model.msg.basic.ImageTextMsg;
import com.zzb.weixin.model.msg.basic.TextMsg;
import com.zzb.weixin.model.msg.basic.VoiceMsg;

/**
 * 处理微信服务器请求的Servlet URL地址：http://xxx/weixin/dealwith.do
 * 
 * 注意：官方文档限制使用80端口哦！
 * 
 */
public class WinXinServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	//TOKEN 是你在微信平台开发模式中设置的哦
	public static final String TOKEN = "3nwk9AihFYMMClSB";

	
	
	/**
	 * 处理微信服务器验证
	 * 
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String signature = request.getParameter("signature");// 微信加密签名
		String timestamp = request.getParameter("timestamp");// 时间戳
		String nonce = request.getParameter("nonce");// 随机数
		String echostr = request.getParameter("echostr");// 随机字符串

		Writer out = response.getWriter();
		if (WeiXinUtil.check(TOKEN, timestamp, nonce, signature)) {
			out.write(echostr);// 请求验证成功，返回随机码
		} else {
			out.write("");
		}
		out.flush();
		out.close();
	}


	
	
	
	/**
	 * 处理微信服务器发过来的各种消息，包括：文本、图片、地理位置、音乐等等
	 * 
	 * 
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		InputStream is  = request.getInputStream();
		OutputStream os = response.getOutputStream();

		try {
			//处理微信消息
			listenerManger.process(is, os);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		listenerManger.close();//关闭Session
	}

	//以下代码为处理微信接收的消息并自动返回指定内容的代码，具体实现内容可自行修改
	private static DefaultListenerManager listenerManger = DefaultListenerManager
			.newInstance();
	static {
		//向监听器中添加事件响应方法，可以添加多个，会遍历执行
		listenerManger.addOnHandleMessageListener(new DefaultHandleMessageListener() {

			@Override
			public boolean onMsg(VoiceMsg msg) {
				TextMsg reMsg = new TextMsg();
				reMsg.setFromUserName(msg.getToUserName());
				reMsg.setToUserName(msg.getFromUserName());
				reMsg.setCreateTime(msg.getCreateTime());
				reMsg.setContent("识别结果: " + msg.getRecognition());
				listenerManger.callback(reMsg);// 回传消息
				return true;
			}


			@Override
			public boolean onMsg(TextMsg msg) {
				if ("1".equals(msg.getContent())) {// 菜单选项1
					System.out.println(msg.getFromUserName());
					TextMsg reMsg = new TextMsg();
					reMsg.setFromUserName(msg.getToUserName());
					reMsg.setToUserName(msg.getFromUserName());
					reMsg.setCreateTime(msg.getCreateTime());
					reMsg.setContent("【菜单】\n" + "1. 功能菜单\n" + "2. 图文消息测试\n"
							+ "3. 图片消息测试\n");
					System.out.println(msg.getFromUserName());
					listenerManger.callback(reMsg);// 回传消息
				} else if ("2".equals(msg.getContent())) {
					// 回复一条消息
					ImageTextData d1 = new ImageTextData(
							"测试",
							"测试",
							"http://zhzhbin1030.vicp.cc/public/images/logo.png",
							"http://zhzhbin1030.vicp.cc/new/overview");
					ImageTextData d2 = new ImageTextData(
							"测试",
							"测试",
							"http://zhzhbin1030.vicp.cc/public/images/logo.png",
							"http://zhzhbin1030.vicp.cc/new/overview");

					ImageTextMsg mit = new ImageTextMsg();
					mit.setFromUserName(msg.getToUserName());
					mit.setToUserName(msg.getFromUserName());
					mit.setCreateTime(msg.getCreateTime());
					try {
						mit.addItem(d1);
						mit.addItem(d2);
					} catch (Exception e) {
						e.printStackTrace();
					}
					listenerManger.callback(mit);
				} else if ("3".equals(msg.getContent())) {
					ImageMsg rmsg = new ImageMsg();
					rmsg.setFromUserName(msg.getToUserName());
					rmsg.setToUserName(msg.getFromUserName());
					rmsg.setPicUrl("http://zhzhbin1030.vicp.cc/public/images/logo.png");
					listenerManger.callback(rmsg);
				} else if ("4".equals(msg.getContent())) {
					TextMsg reMsg = new TextMsg();
					reMsg.setFromUserName(msg.getToUserName());
					reMsg.setToUserName(msg.getFromUserName());
					reMsg.setCreateTime(msg.getCreateTime());
					reMsg.setContent("<a href=\"http://mp.weixin.qq.com/mp/getmasssendmsg?__biz=MzA3MzQyMDkxNQ==#wechat_webview_type=1&wechat_redirect\">查看历史消息</a>");
					System.out.println(msg.getFromUserName());
					listenerManger.callback(reMsg);// 回传消息
				} else {
					TextMsg reMsg = new TextMsg();
					reMsg.setFromUserName(msg.getToUserName());
					reMsg.setToUserName(msg.getFromUserName());
					reMsg.setCreateTime(msg.getCreateTime());

					reMsg.setContent("消息命令未支持，谢谢您的支持！");

					listenerManger.callback(reMsg);// 回传消息
				}
				return true;
			}

			@Override
			public boolean onMsg(EventMsg msg) {
				switch (msg.getEvent()) {
				case SUBSCRIBE:// 订阅
					System.out.println("关注人：" + msg.getFromUserName());
					System.out.println("参数值：" + msg.getEventKey());

					TextMsg reMsg = new TextMsg();
					reMsg.setFromUserName(msg.getToUserName());
					reMsg.setToUserName(msg.getFromUserName());
					reMsg.setCreateTime(msg.getCreateTime());

					reMsg.setContent("【菜单】\n" + "1. 功能菜单\n" + "2. 图文消息测试\n"
							+ "3. 图片消息测试\n");

					listenerManger.callback(reMsg);// 回传消息
					return true;
				case UNSUBSCRIBE:// 取消订阅
					System.out.println("取消关注：" + msg.getFromUserName());
					return true;
				case CLICK:// 点击事件
					System.out.println("用户：" + msg.getFromUserName());
					System.out.println("点击Key：" + msg.getEventKey());
					TextMsg reMsg2 = new TextMsg();
					reMsg2.setFromUserName(msg.getToUserName());
					reMsg2.setToUserName(msg.getFromUserName());
					reMsg2.setCreateTime(msg.getCreateTime());

					reMsg2.setContent("【菜单】\n" + "1. 功能菜单\n" + "2. 图文消息测试\n"
							+ "3. 图片消息测试\n");

					listenerManger.callback(reMsg2);// 回传消息
					return true;
				default:
					return false;
				}
			}
		});
	}

}
